<template>
    <div class="madp-auto-pull-group">
        <basic-container>
            <div class="madp-search">
                <el-input placeholder="请输入群活码名称" v-model.trim="qrcodeName" @input="qrcodeName = qrcodeName.replace(/\s+/g, '')"></el-input>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleClear">清空</el-button>
            </div>
            <div style="margin-bottom: 10px">
                <el-button type="primary" @click="handleAddGroup">新增拉群</el-button>
            </div>
            <div class="madp-table">
                <el-table
                    :header-cell-style="{
                        background: 'rgb(255, 191, 191)',
                        color: 'rgb(44,44,44)'
                    }"
                    :stripe="true"
                    :data="tableData"
                    style="width: 100%"
                >
                    <el-table-column align="center" width="50" label="序号">
                        <template slot-scope="scope">
                            <span v-text="getIndex(scope.$index)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="qrcodeUrl" align="center" label="二维码" width="180">
                        <template slot-scope="scope">
                            <div v-if="scope.row.qrcodeUrl" class="madp-table-img">
                                <img
                                    :src="scope.row.qrcodeUrl"
                                    alt
                                    @click="
                                        isLargeImgShow = true;
                                        largeImgUrl = scope.row.qrcodeUrl;
                                    "
                                />
                            </div>
                            <div v-else>—</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="qrcodeName" align="center" label="名称">
                        <template slot-scope="scope">
                            <div>{{ scope.row.qrcodeName || '—' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="checkMemberList" align="center" label="使用成员">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" width="200" trigger="hover" v-if="scope.row.employees && scope.row.employees.length > 0">
                                <div>
                                    <el-tag type="primary" style="margin: 2px" v-for="(item, index) in scope.row.employees" :key="index">{{ item }}</el-tag>
                                </div>
                                <div slot="reference">
                                    <el-tag type="primary" style="margin: 2px" v-for="(item, index) in scope.row.employees ? scope.row.employees.slice(0, 2) : []" :key="index">{{ item }}</el-tag>
                                    <el-tag type="primary" style="margin: 2px" v-if="scope.row.employees && scope.row.employees.length > 2">...</el-tag>
                                </div>
                            </el-popover>
                            <div v-else>—</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tags" align="center" label="标签">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" width="200" trigger="hover" v-if="scope.row.tags && scope.row.tags.length > 0">
                                <div>
                                    <el-tag type="primary" v-for="(item, index) in scope.row.tags" :key="index">{{ item }}</el-tag>
                                </div>
                                <div slot="reference">
                                    <el-tag type="primary" v-for="(item, index) in scope.row.tags ? scope.row.tags.slice(0, 2) : []" :key="index">{{ item }}</el-tag>
                                    <el-tag type="primary" v-if="scope.row.tags && scope.row.tags.length > 2">...</el-tag>
                                </div>
                            </el-popover>
                            <div v-else>—</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="contactNum" align="center" width="80" label="客户数">
                        <template slot-scope="scope">
                            <div>
                                {{ scope.row.contactNum === 0 ? 0 : scope.row.contactNum || '—' }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="groupChat" align="center" label="群聊">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" width="200" trigger="hover" v-if="scope.row.rooms && scope.row.rooms.length > 0">
                                <div>
                                    <el-tag type="primary" v-for="(item, index) in scope.row.rooms" :key="index">{{ item.roomName }}</el-tag>
                                </div>
                                <div slot="reference">
                                    <el-tag type="primary" v-for="(item, index) in scope.row.rooms ? scope.row.rooms.slice(0, 2) : []" :key="index">{{ item.roomName }}</el-tag>
                                    <el-tag type="primary" v-if="scope.row.rooms && scope.row.rooms.length > 2">...</el-tag>
                                </div>
                            </el-popover>
                            <div v-else>—</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdTime" align="center" label="创建时间">
                        <template slot-scope="scope">
                            <div>{{ scope.row.createdTime || '—' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleDetails(scope.row)">详情</el-button>
                            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
                            <el-button type="text" @click="handleDel(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row>
                    <el-col :span="24" class="toolbar" style="margin-top: 5px">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page.currentPage"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="page.pageSize"
                            layout="total, prev, pager, next, jumper"
                            :total="page.total"
                            style="float: right"
                        ></el-pagination>
                    </el-col>
                </el-row>
            </div>
        </basic-container>
        <!-- 新建拉群弹框 开始 -->
        <el-dialog
            :title="pullGroupTitle"
            :visible.sync="dialogShow"
            :close-on-click-modal="false"
            top="2vh"
            custom-class="madp-pull-group-dialog"
            append-to-body
            width="80%"
            :before-close="
                () => {
                    dialogShow = false;
                    selectedMembers = [];
                }
            "
        >
            <div class="madp-pull-group-content">
                <div class="madp-left-wrapper">
                    <div style="text-align: center">客服账号</div>
                    <div class="madp-leading-wrapper">
                        <div class="madp-user-wrapper">
                            <!-- <img src="" alt /> -->
                            <i class="el-icon-user-solid"></i>
                        </div>
                        <div class="madp-user-info">
                            <div>
                                {{ formGroup.leadingWords ? formGroup.leadingWords : '您好！' }}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="madp-right-wrapper">
                    <div>
                        <el-form ref="formGroup" :model="formGroup" label-width="100px" :rules="formRules">
                            <el-form-item label="扫码名称:" prop="qrcodeName">
                                <el-input
                                    v-model.trim="formGroup.qrcodeName"
                                    placeholder="请输入扫码名称"
                                    maxlength="30"
                                    @input="formGroup.qrcodeName = formGroup.qrcodeName.replace(/\s+/g, '')"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="添加验证:" prop="isVerified">
                                <el-radio-group v-model="formGroup.isVerified">
                                    <el-radio :label="1">需验证</el-radio>
                                    <el-radio :label="2">直接通过</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="使用成员:" prop="checkMemberList">
                                <div class="madp-member-list" v-if="formGroup.checkMemberList && formGroup.checkMemberList.length > 0">
                                    <el-tag type="info" v-for="(item, index) in formGroup.checkMemberList" :key="index">{{ item.employeeName }}</el-tag>
                                </div>
                                <el-button type="primary" icon="el-icon-plus" @click="handleAddMemberDialog">添加成员</el-button>
                            </el-form-item>
                            <el-form-item label="入群打标签:">
                                <div class="madp-tag-list">
                                    <ul>
                                        <li class="madp-tags-wrapper" v-for="(item, index) in tags" :key="index">
                                            <div class="madp-tag-name">{{ item.groupName }}</div>
                                            <div class="madp-tag-content">
                                                <el-tag
                                                    class="madp-tag"
                                                    v-for="(inner, i) in item.tagNameList"
                                                    :key="i"
                                                    :color="inner.isSelected ? theme : '#ffffff'"
                                                    :style="inner.isSelected ? 'color: #ffffff' : '#000000'"
                                                    @click="handleSelectTag(item, inner)"
                                                    >{{ inner.name }}</el-tag
                                                >
                                                <el-button class="madp-tag-add" type="text" icon="el-icon-plus" @click="handleAddLabelDialog(item.groupId, item.groupName)">新建标签</el-button>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </el-form-item>
                            <el-form-item label="入群引导语:" prop="leadingWords">
                                <div class="madp-guide-language">
                                    <div>
                                        <el-input
                                            type="textarea"
                                            v-model="formGroup.leadingWords"
                                            rows="4"
                                            resize="none"
                                            :onkeyup="(formGroup.leadingWords = formGroup.leadingWords.replace(/\s+/g, ''))"
                                            @focus="selectionStart = 0"
                                        ></el-input>
                                    </div>
                                    <div style="margin-top: 10px">
                                        <span>点击插入</span>
                                        <el-button class="madp-guide-language-btn" type="primary" @click="insertCustomerName">客户名称</el-button>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item label="添加群聊:" prop="groupChat">
                                <div>
                                    <p>
                                        可添加多个群聊，当前面的群人数达到上限后，自动发送后面的群二维码。即当第一个群达到人数上限，客户自动扫码会添加第二个客服，然后进入第二个群聊，依次往后进行。因系统无法判断群二维码是否真实有效，请您准确上传群对应的群二维码，否则会影响拉群效果
                                    </p>
                                </div>
                                <div class="madp-group-chat">
                                    <el-table
                                        :header-cell-style="{
                                            background: 'rgb(255, 191, 191)',
                                            color: 'rgb(44,44,44)'
                                        }"
                                        stripe
                                        :data="formGroup.groupChat"
                                        row-key="roomId"
                                    >
                                        <el-table-column prop="roomName" align="center" label="群名称(人数)">
                                            <template slot-scope="scope">
                                                {{ scope.row.roomName + '（' + scope.row.currentNum + '）' }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="roomMax" align="center" label="群人数上限"></el-table-column>
                                        <el-table-column prop="QrCode" align="center" label="群二维码">
                                            <template slot-scope="scope">
                                                <el-upload
                                                    class="madp-avatar-uploader"
                                                    :show-file-list="false"
                                                    accept=".jpg, .jpeg"
                                                    :auto-upload="false"
                                                    action="#"
                                                    :on-change="(file) => uploadChangeFile(file, scope.row)"
                                                    :before-upload="handleBeforeUpload"
                                                >
                                                    <img v-if="scope.row.roomQrcodeUrl" :src="scope.row.roomQrcodeUrl" class="avatar" alt />
                                                    <div class="madp-avatar-uploader-icon" v-else>
                                                        <i class="el-icon-plus"></i>
                                                    </div>
                                                </el-upload>
                                            </template>
                                        </el-table-column>
                                        <el-table-column align="center" label="操作">
                                            <template slot-scope="scope">
                                                <el-button type="text" @click="handleDeleteGroupChat(scope.row)">删除</el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                                <div style="margin-top: 10px">
                                    <el-button icon="el-icon-plus" @click="handleGroupChatDialog">选择群聊</el-button>
                                </div>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="madp-dialog-footer">
                        <el-button
                            @click="
                                dialogShow = false;
                                selectedMembers = [];
                            "
                            >取消</el-button
                        >
                        <el-button type="primary" :loading="submitLoading" @click="handlePullGroup('formGroup')">确定</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>
        <!-- 新建拉群弹框 结束 -->
        <!-- 添加成员弹窗 开始 -->
        <div v-if="dialogShow">
            <AddMember
                ref="addMember"
                @getMemberList="getMemberList"
                @closepop="
                    () => {
                        this.addMemberDialog = false;
                    }
                "
                :showAddMember="addMemberDialog"
                :selectedMembers="selectedMembers"
            ></AddMember>
        </div>
        <!-- 添加成员弹窗 结束 -->
        <!-- 新建标签 开始 -->
        <el-dialog title="新建标签" :visible.sync="addTagDialog" :close-on-click-modal="false" custom-class="madp-dialog-add-member" append-to-body width="50%">
            <div class="madp-add-tag-content">
                <el-form ref="addTagData" :model="addTagData" label-width="90px">
                    <el-form-item label="分组名称:">
                        <el-input v-model.trim="addTagData.groupName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="标签名称:">
                        <p>每个标签名称最多15个字符，同时新建多个标签时，请用“空格”隔开</p>
                        <el-input v-model="addTagData.tagName" @input="addTagData.tagName = addTagData.tagName.replace(/\s{2}/, ' ')"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer">
                <el-button @click="addTagDialog = false">取消</el-button>
                <el-button type="primary" :loading="addTagLoading" @click="handleTag">确定</el-button>
            </div>
        </el-dialog>
        <!-- 新建标签 结束 -->
        <!-- 选择群聊 开始 -->
        <el-dialog title="选择群聊" :visible.sync="groupChatDialog" :close-on-click-modal="false" top="10vh" custom-class="madp-dialog-add-member madp-dialog-add-group" append-to-body width="45%">
            <div class="madp-group-chat-content">
                <div>
                    <el-input placeholder="请输入群名称" v-model.trim="name">
                        <i slot="suffix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-button type="primary" @click="handleSearchRoom">查询</el-button>
                </div>
                <div class="madp-dialog-add-group-table">
                    <el-table
                        ref="multipleTable"
                        :data="groupChatList.list"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleGroupChatChange"
                        :row-key="getRowKeys"
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        :stripe="true"
                    >
                        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
                        <el-table-column prop="groupChat" label="群聊">
                            <template slot-scope="scope">
                                <div class="madp-content-display">
                                    <img style="width: 52px; height: 52px" src="/img/user.png" alt />
                                    <div class="madp-content-text">
                                        <p>{{ scope.row.roomName }}</p>
                                        <p class="madp-content-desc">
                                            {{ scope.row.currentNum + '/' + scope.row.roomMax }}
                                        </p>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="madp-pagination">
                    <el-pagination
                        background
                        @size-change="groupChatListHandleSizeChange"
                        @current-change="groupChatListHandleCurrentChange"
                        :current-page="groupChatList.current"
                        :page-sizes="[10, 20, 30, 50, 100]"
                        :page-size="groupChatList.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="groupChatList.total"
                    ></el-pagination>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="groupChatDialog = false">取消</el-button>
                <el-button type="primary" @click="handleGroupChat">确定</el-button>
            </div>
        </el-dialog>
        <!-- 选择群聊 结束 -->
        <!-- 详情弹框 开始 -->
        <el-dialog title="自动拉群详情" :visible.sync="detailsDialog" :close-on-click-modal="false" top="5vh" custom-class="madp-dialog-add-member" append-to-body width="1000px">
            <div class="madp-detail-content">
                <el-row>
                    <el-col :span="7">
                        <div class="madp-detail-content-left">
                            <div class="madp-img madp-common">
                                <img width="100%" height="100%" :src="detailData.QrCode" alt />
                            </div>
                            <div class="madp-title madp-common">
                                <p>{{ detailTitle }}</p>
                            </div>
                            <div class="madp-download madp-common">
                                <el-button type="primary" @click="handleDownloadQrCode">下载活码</el-button>
                            </div>
                            <div class="madp-edit madp-common">
                                <el-button @click="handleModify(detailInfo)">修改</el-button>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="16" :offset="1">
                        <div class="madp-detail-content-right">
                            <el-row>
                                <el-col :span="4">创建日期:</el-col>
                                <el-col :span="16" :offset="4" :pull="3">{{ detailInfo.createdTime }}</el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="4">是否验证:</el-col>
                                <el-col :span="16" :offset="4" :pull="3">
                                    {{ detailInfo.isVerified | transIsVerified }}
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="4">使用成员:</el-col>
                                <el-col :span="16" :offset="4" :pull="3">
                                    <el-tag
                                        class="madp-tag"
                                        type="info"
                                        v-for="item in detailInfo.employees"
                                        :key="item.employeeId"
                                        :color="theme"
                                        :style="{
                                            color: '#ffffff'
                                        }"
                                        >{{ item.employeeName }}</el-tag
                                    >
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="4">入群标签:</el-col>
                                <el-col :span="16" :offset="4" :pull="3">
                                    <div class="madp-tag-list">
                                        <ul>
                                            <li
                                                class="madp-tags-wrapper"
                                                v-for="(item, index) in newTags"
                                                :key="index"
                                                :class="{
                                                    'madp-tags-last': index === newTags.length - 1
                                                }"
                                            >
                                                <div class="madp-tag-name">{{ item.groupName }}</div>
                                                <div class="madp-tag-content">
                                                    <el-tag
                                                        class="madp-tag"
                                                        v-for="(inner, i) in item.tagNameList"
                                                        :key="i"
                                                        :color="theme"
                                                        :style="{
                                                            color: '#ffffff'
                                                        }"
                                                        >{{ inner.name }}</el-tag
                                                    >
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="4">入群引导语:</el-col>
                                <el-col :span="16" :offset="4" :pull="3">
                                    {{ detailInfo.leadingWords }}
                                </el-col>
                            </el-row>
                        </div>
                    </el-col>
                </el-row>
                <div class="madp-detail-content-bottom">
                    <div class="madp-detail-content-bottom-title">共有{{ detailInfo.roomNum }}个群聊</div>
                    <el-table
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        :stripe="true"
                        :data="detailInfo.rooms"
                        style="width: 100%"
                        row-key="roomId"
                    >
                        <el-table-column prop="roomName" align="center" label="群名称(人数)">
                            <template slot-scope="scope">
                                {{ scope.row.roomName + '（' + scope.row.currentNum + '）' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="roomMax" align="center" label="群人数上限"></el-table-column>
                        <el-table-column prop="QrCode" align="center" label="群二维码">
                            <template slot-scope="scope">
                                <img
                                    :src="scope.row.roomQrcodeUrl"
                                    class="madp-detail-content-bottom-avatar"
                                    alt
                                    @click="
                                        isLargeImgShow = true;
                                        largeImgUrl = scope.row.roomQrcodeUrl;
                                    "
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="detailsDialog = false">关闭</el-button>
            </div>
        </el-dialog>
        <!-- 详情弹框 结束 -->
        <large-img
            :visible="isLargeImgShow"
            :imgUrl="largeImgUrl"
            @close="
                isLargeImgShow = false;
                imgUrl = '';
            "
        />
    </div>
</template>

<script>
import AddMember from '@/components/wechat/add-member';
import LargeImg from '@/components/large-img';
import { getStore } from '../../../util/store';
import Sortable from 'sortablejs';
import {
    getWorkRoomAutoPull,
    postWorkRoomAutoPull,
    putWorkRoomAutoPull,
    getDetails,
    getWorkRoom,
    getCustomerLabelList,
    postTagList,
    sysFileUpload,
    delWorkRoomAutoPull
} from '@/api/customer-group/autopullgroup';
import { mapGetters } from 'vuex';
export default {
    name: 'index',
    components: { AddMember, LargeImg },
    computed: {
        ...mapGetters(['theme'])
    },
    data() {
        return {
            //搜索参数
            qrcodeName: '',
            tableData: [],
            // 分页
            page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            dialogShow: false,
            pullGroupTitle: '',
            formGroup: {
                qrcodeName: '', //扫码名称
                isVerified: 1, //验证
                leadingWords: '', //引导语
                checkMemberList: [],
                groupChat: []
            },
            formRules: {
                qrcodeName: [{ required: true, message: '请输入扫码名称' }],
                isVerified: [{ required: true, message: '请选择是否验证' }],
                checkMemberList: [{ required: true, message: '请添加成员' }],
                leadingWords: [{ required: true, message: '请输入引导语' }],
                groupChat: [{ required: true, message: '请选择群聊' }]
            },
            //标签
            tags: [],
            //选中的标签
            checkedTags: [],
            //添加成员弹框
            addMemberDialog: false,
            //选中的成员id
            employeeList: [],
            //新建标签弹框
            addTagDialog: false,
            //新建标签数据
            addTagData: {},
            //选择群聊
            groupChatDialog: false,
            name: '',
            //群聊数据
            groupChatList: {
                list: [],
                total: 0,
                size: 10,
                current: 1
            },
            checkGroupChatList: [],
            // 弹窗开关
            detailsDialog: false,
            // 详情标题
            detailTitle: '',
            // 详情数据
            detailData: {},
            // 详情信息
            detailInfo: {},
            submitLoading: false,
            // 图片路径
            imageUrl: '',
            // 按钮loading
            addTagLoading: false,
            getRowKeys(row) {
                return row.roomId;
            },
            // 是否大图显示
            isLargeImgShow: false,
            // 大图路径
            largeImgUrl: '',
            newTags: [], //详情中过滤后的标签
            selectedMembers: [] // 选中成员
        };
    },
    filters: {
        transIsVerified(val) {
            switch (val) {
                case 1:
                    return '需要验证';
                case 2:
                    return '直接通过';
                default:
                    break;
            }
        }
    },
    mounted() {
        this.getList(this.page);
        this.fetchLabelList();
    },
    methods: {
        //获取表格序号
        getIndex($index) {
            return (this.page.currentPage - 1) * this.page.pageSize + $index + 1;
        },
        // 移动内容
        rowMove() {
            const tbody = document.querySelector('.madp-group-chat tbody');
            const _this = this;
            Sortable.create(tbody, {
                onEnd({ newIndex, oldIndex }) {
                    const currRow = _this.formGroup.groupChat.splice(oldIndex, 1)[0];
                    _this.formGroup.groupChat.splice(newIndex, 0, currRow);
                }
            });
        },
        //列表
        getList(page, params) {
            let obj = Object.assign(
                {
                    current: page.currentPage,
                    size: page.pageSize,
                    permission: 'ALL'
                },
                params
            );
            getWorkRoomAutoPull(obj).then((res) => {
                if (res.data.code === 0) {
                    this.tableData = res.data.data.records;
                    this.page.total = res.data.data.total;
                }
            });
        },
        /*
         * 列表下载
         * */
        handleDownload(data) {
            let a = document.createElement('a'); // 创建一个a节点插入的document
            let event = new MouseEvent('click'); // 模拟鼠标click点击事件
            a.download = data.qrcodeName;
            a.href = data.qrcodeUrl; // 将图片的src赋值给a节点的href
            a.dispatchEvent(event);
        },
        /*
         * 删除
         * */
        handleDel(data) {
            this.$confirm('删除后不可恢复，确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    delWorkRoomAutoPull(data.workRoomAutoPullId).then((res) => {
                        if (res.data.code === 0) {
                            this.$message.success('删除成功');
                            if (this.page.currentPage > 1 && this.tableData.length === 1) {
                                this.page.currentPage -= 1;
                            }
                            this.getList(this.page);
                        }
                    });
                })
                .catch(() => {});
        },
        /*
         * 下载活码
         * */
        handleDownloadQrCode() {
            let a = document.createElement('a'); // 创建一个a节点插入的document
            let event = new MouseEvent('click'); // 模拟鼠标click点击事件
            a.download = this.detailTitle;
            a.href = this.detailData.QrCode; // 将图片的src赋值给a节点的href
            a.dispatchEvent(event);
            this.$nextTick(() => {
                this.$message({ type: 'success', message: '下载成功' });
            });
        },
        /*
         * 详情修改
         * */
        handleModify(data) {
            this.detailsDialog = false;
            this.handleEdit(data);
        },
        /*
         * 详情
         * */
        handleDetails(data) {
            this.detailTitle = data.qrcodeName;
            this.detailData.QrCode = data.qrcodeUrl;
            this.detailsDialog = true;
            getDetails(data.workRoomAutoPullId)
                .then((res) => {
                    this.detailsDialog = false;
                    if (res.data.code === 0) {
                        this.detailInfo = res.data.data;
                        let selectedTags = res.data.data.selectedTags;
                        let newTags = JSON.parse(JSON.stringify(this.tags));
                        newTags.forEach((item) => {
                            item.tagNameList = item.tagNameList.filter((it) => selectedTags.includes(it.id));
                        });
                        newTags = newTags.filter((item) => item.tagNameList && item.tagNameList.length > 0);
                        this.newTags = newTags;
                    }
                })
                .catch(() => {
                    this.detailsDialog = false;
                });
        },
        /*
         * 表格编辑
         * */
        handleEdit(data) {
            getDetails(data.workRoomAutoPullId)
                .then((res) => {
                    if (res.data.code === 0) {
                        let data = res.data.data;
                        this.formGroup = {
                            ...data,
                            groupChat: data.rooms,
                            checkMemberList: data.employees
                        };
                        this.tags = this.tags.map((item) => ({
                            ...item,
                            tagNameList: item.tagNameList.map((it) => ({
                                ...it,
                                isSelected: data.selectedTags.includes(it.id) ? 1 : 0
                            }))
                        }));
                        this.checkedTags = [...data.selectedTags];
                        this.selectedMembers = data.employees;
                    }
                })
                .then(() => {
                    this.pullGroupTitle = '编辑拉群';
                    this.dialogShow = true;
                    this.$nextTick(() => {
                        this.rowMove();
                    });
                });
        },
        //上传二维码
        handleBeforeUpload(file) {
            console.log('file', file);
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 <= 5;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isJPG && isLt2M;
        },
        handleAvatarSuccess(res, file, row) {
            this.formGroup.groupChat = this.formGroup.groupChat.map((item) => ({
                ...item,
                roomQrcodeUrl: URL.createObjectURL(file.raw)
            }));
            // this.imageUrl = URL.createObjectURL(file.raw)
        },
        uploadChangeFile(file, row) {
            this.sysFileUploadFn(file, row);
        },
        sysFileUploadFn(file, row) {
            let fd = new FormData();
            fd.append('file', file.raw);
            sysFileUpload(fd).then((res) => {
                if (res.data.code === 0) {
                    let fileMsg = res.data.data;
                    this.formGroup.groupChat = this.formGroup.groupChat.map((item) => ({
                        ...item,
                        roomQrcodeUrl: item.roomId === row.roomId ? fileMsg.url : item.roomQrcodeUrl
                    }));
                }
            });
        },
        /*新建拉群*/
        handleAddGroup() {
            this.dialogShow = true;
            this.pullGroupTitle = '新建拉群';
            this.formGroup = {
                qrcodeName: '', //扫码名称
                isVerified: 1, //验证
                leadingWords: '', //引导语
                checkMemberList: [],
                groupChat: []
            };
            this.fetchLabelList();
            this.$nextTick(() => {
                this.$refs.formGroup.clearValidate();
            });
        },
        /*
         * 删除群聊
         * */
        handleDeleteGroupChat(data) {
            this.$confirm('确定删除此条群聊么?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.formGroup.groupChat.splice(this.formGroup.groupChat.indexOf(data), 1);
                })
                .catch(() => {});
        },
        /*
         * 选择群聊
         * */
        handleGroupChatDialog(params) {
            let that = this;
            let obj = {
                name: this.name,
                current: this.groupChatList.current,
                size: this.groupChatList.size
            };
            getWorkRoom(obj).then((res) => {
                if (res.data.code === 0) {
                    this.groupChatList.list = res.data.data.data.records || [];
                    this.groupChatList.total = res.data.data.data.total;
                    this.$nextTick(() => {
                        if (that.$refs.multipleTable) {
                            that.$refs.multipleTable.clearSelection();
                        }
                        that.groupChatList.list.forEach((row) => {
                            for (let j in that.formGroup.groupChat) {
                                if (row.roomId === that.formGroup.groupChat[j].roomId) {
                                    that.$refs.multipleTable.toggleRowSelection(row, true);
                                    break;
                                }
                            }
                        });
                    });
                }
            });
            this.groupChatDialog = true;
        },
        //选择群聊 查询
        handleSearchRoom() {
            this.groupChatList.current = 1;
            this.handleGroupChatDialog();
        },
        //选择群聊 确定
        handleGroupChat() {
            let selectedGroup = {};
            let selectedGroupId = [];

            this.formGroup.groupChat.forEach((item) => {
                selectedGroup[item.roomId] = item;
                selectedGroupId.push(item.roomId);
            });
            let newSelected = this.checkGroupChatList.map((item) => {
                if (selectedGroupId.includes(item.roomId)) {
                    item = selectedGroup[item.roomId];
                }
                return item;
            });
            this.formGroup.groupChat = [...newSelected];
            this.groupChatDialog = false;
            this.rowMove();
        },
        handleGroupChatChange(data) {
            this.checkGroupChatList = data;
        },
        /*
         * 标签选择
         * */
        handleSelectTag(item, list) {
            const index = this.checkedTags.indexOf(list.id);
            if (index > -1) {
                this.checkedTags.splice(index, 1);
            } else {
                this.checkedTags.push(list.id);
            }
            item.tagNameList.filter((inner) => {
                if (inner.id === list.id) {
                    //动态设置一个属性，方便显示已选中标签
                    this.$set(inner, 'isSelected', index > -1 ? 0 : 1);
                    return true;
                }
            });
        },
        /*获取标签组*/
        fetchLabelList() {
            getCustomerLabelList().then((res) => {
                if (res.data.code === 0) {
                    this.tags = res.data.data;
                }
            });
        },
        /*
         * 插入客户名称
         * */
        insertCustomerName() {
            let start = 0;
            if (this.selectionStart) {
                start = this.selectionStart;
            } else {
                const textarea = document.getElementsByClassName('el-textarea__inner')[0];
                start = textarea.selectionStart; // input 第0个字符到选中的字符
            }
            this.selectionStart = start;
            this.formGroup.leadingWords = this.formGroup.leadingWords.slice(0, start) + '##客户名称##' + this.formGroup.leadingWords.slice(start);
        },
        /*
         * 新建标签 （确定）
         * */
        handleTag() {
            this.addTagLoading = true;
            if (!this.addTagData.tagName) {
                this.$message({ type: 'warning', message: '请输入标签名称' });
                return false;
            }
            //将标签拆分成字符串
            const arr = this.addTagData.tagName.split(' ');
            const tagNameList = arr.filter((item) => {
                return item;
            });
            postTagList({ groupId: this.addTagData.groupId, tagNameList })
                .then((res) => {
                    if (res.data.code === 0) {
                        this.$message({ type: 'success', message: '新建成功' });
                        this.addTagDialog = false;
                        this.addTagData.tagName = '';
                        this.fetchLabelList();
                    }
                    this.addTagLoading = false;
                })
                .catch(() => {
                    this.addTagLoading = false;
                });
        },
        /*
         * 新建标签
         * */
        handleAddLabelDialog(groupId, groupName) {
            this.addTagData.groupName = groupName;
            this.addTagData.groupId = groupId;
            this.addTagDialog = true;
        },
        /*
         * 添加成员
         * */
        handleAddMemberDialog() {
            this.addMemberDialog = true;
        },
        getMemberList(data) {
            this.formGroup.checkMemberList = data;
            this.selectedMembers = data;
            this.employeeList = data.map((item) => item.employeeId);
        },
        /*
         * 新建拉群(确定)
         * */
        handlePullGroup(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let corpId = getStore({ name: 'corps' }).corpId;
                    //将群聊id提出来，并转为字符串
                    let rooms = JSON.parse(JSON.stringify(this.formGroup.groupChat));
                    let isHaveQrcode = true;
                    rooms.forEach((item) => {
                        if (!item.roomQrcodeUrl) {
                            isHaveQrcode = false;
                        }
                    });
                    if (!isHaveQrcode) {
                        this.$message.error('请在选择的群聊中上传二维码');
                        return;
                    }
                    // let rooms = this.formGroup.groupChat.map(item => item.roomId).toString();
                    //将选中的标签转化为字符串
                    let tags = this.checkedTags.toString();
                    //成员id
                    let employees = this.employeeList.toString();
                    if (this.pullGroupTitle === '新建拉群') {
                        let obj = Object.assign({ tags, employees, rooms, corpId }, this.formGroup);
                        delete obj.groupChat;
                        delete obj.checkMemberList;
                        postWorkRoomAutoPull(obj)
                            .then((res) => {
                                if (res.data.code === 0) {
                                    this.$message({
                                        type: 'success',
                                        message: '新增成功'
                                    });
                                    this.dialogShow = false;
                                    this.getList(this.page);
                                    this.selectedMembers = [];
                                }
                                this.submitLoading = false;
                            })
                            .catch(() => {
                                this.submitLoading = false;
                            });
                    } else if (this.pullGroupTitle === '编辑拉群') {
                        let obj = Object.assign({ corpId }, { ...this.formGroup, tags, employees, rooms });
                        delete obj.groupChat;
                        delete obj.checkMemberList;
                        delete obj.roomNum;
                        delete obj.qrcodeUrl;
                        delete obj.createdTime;
                        delete obj.selectedTags;
                        putWorkRoomAutoPull(obj)
                            .then((res) => {
                                if (res.data.code === 0) {
                                    this.$message({
                                        type: 'success',
                                        message: '修改成功'
                                    });
                                    this.dialogShow = false;
                                    this.getList(this.page);
                                    this.selectedMembers = [];
                                }
                                this.submitLoading = false;
                            })
                            .catch(() => {
                                this.submitLoading = false;
                            });
                    } else {
                    }
                } else {
                    return false;
                }
            });
        },
        /*
         * 清空
         * */
        handleClear() {
            this.qrcodeName = '';
            this.getList(this.page);
        },
        /*
         * 搜索
         * */
        handleSearch() {
            this.page.currentPage = 1;
            this.getList(this.page, { qrcodeName: this.qrcodeName });
        },
        /**
         * 分页-改变每页记录条数触发查询
         **/
        handleSizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.getList(this.page);
        },
        /**
         * 分页-改变当前页码记录条数触发查询
         **/
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage;
            this.getList(this.page);
        },
        // 分页
        groupChatListHandleSizeChange(size) {
            this.groupChatList.size = size;
            this.handleGroupChatDialog();
        },
        groupChatListHandleCurrentChange(current) {
            this.groupChatList.current = current;
            this.handleGroupChatDialog();
        }
    }
};
</script>

<style scoped lang="scss">
.madp-auto-pull-group {
    .madp-search {
        display: flex;
        justify-content: flex-end;

        .el-input {
            width: 230px;
            margin-right: 5px;
        }
    }
}

/*新建拉群*/
/deep/ .madp-pull-group-dialog .el-dialog__body {
    background: #eeeeee;
}

.el-dialog {
    .madp-pull-group-content {
        display: flex;

        .madp-left-wrapper {
            flex: 0.3;
            padding: 0 10px;
            background: #ffffff;

            .madp-leading-wrapper {
                display: flex;
                margin-top: 10px;

                .madp-user-wrapper {
                    width: 80px;
                    height: 80px;
                    border: 1px solid #eeeeee;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 60px;
                }

                .madp-user-info {
                    flex: 1;
                    margin-left: 10px;
                    padding: 10px;
                    border-radius: 10px;
                    background: #eeeeee;
                }
            }
        }

        .madp-right-wrapper {
            flex: 1;
            margin-left: 20px;
            padding: 30px 15px;
            background: #ffffff;

            .madp-member-list {
                max-height: 300px;
                overflow: auto;
                margin-bottom: 10px;
                background: #eeeeee;

                .el-tag {
                    margin: 0 5px 10px;
                }
            }

            .madp-tag-list {
                width: 100%;
                min-height: 100px;
                padding: 5px;
                background: #eeeeee;

                .madp-tags-wrapper {
                    display: flex;
                    align-items: center;
                    margin-bottom: 10px;

                    .madp-tag-name {
                        margin-right: 15px;
                        padding: 0 20px;
                        border: 1px solid #dcdfe6;
                        border-radius: 4px;
                        font-size: 14px;
                        background-color: #ffffff;
                    }

                    .madp-tag {
                        margin-right: 10px;
                        background: #dddddd;
                        color: #000000;
                        cursor: pointer;
                        user-select: none;
                    }

                    .madp-tag-add {
                        margin-left: 5px;
                    }
                }
            }
        }

        .madp-dialog-footer {
            display: flex;
            justify-content: flex-end;
        }
    }
}

/deep/ .madp-dialog-add-member .el-dialog__body {
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
}

.madp-dialog-add-group-table {
    margin-top: 10px;
    max-height: 55vh;
    overflow: auto;
}

/*添加成员*/
.madp-add-member-content {
    .madp-content-left {
        min-height: 200px;
        padding: 0 5px;
        border-right: 2px solid #dddddd;
    }

    .madp-content-right {
        min-height: 200px;
        padding: 0 5px;

        .madp-content-right-list {
            display: flex;
            /*justify-content: space-around;*/
            align-items: center;
            padding-left: 30px;

            .madp-list-name {
                flex: 1;
            }
        }
    }
}

/*新建标签*/
.madp-add-tag-content {
    padding: 0 50px;
}

/*选择群聊*/
.madp-group-chat-content {
    // padding-right: 60px;

    .el-input {
        width: 400px;
    }

    .madp-group-chat-wrapper {
        .madp-group-chat-list {
            display: flex;
            margin-top: 10px;
            padding-bottom: 5px;
            border-bottom: 1px solid #dddddd;

            .madp-list-left {
                margin-right: 5px;
                width: 60px;
                height: 60px;
            }

            .madp-list-right {
                flex: 1;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }
}

/*详情*/
.madp-detail-content {
    // border: 1px solid #eeeeee;
    max-height: 70vh;
    overflow: auto;

    .el-col {
        margin-bottom: 0;
    }
    &-left {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .madp-common {
            margin: 10px auto;
            width: 130px;
            text-align: center;
            .el-button {
                width: 100%;
            }
        }
        .madp-img {
            width: 120px;
            height: 120px;
            border: 1px solid #eeeeee;
        }
    }
    &-right {
        border-left: 1px solid #e6e6e6;
        min-height: 35vh;
        overflow: auto;
        .el-col {
            margin-bottom: 10px;
        }
        .el-col-4 {
            text-align: right;
            color: #999999;
        }

        .madp-tag {
            margin-right: 10px;
            user-select: none;
        }

        .madp-tag-list {
            width: 100%;

            .madp-tags-wrapper {
                display: flex;
                margin-bottom: 10px;
                &.madp-tags-last {
                    margin-bottom: 0;
                }

                .madp-tag-name {
                    margin-right: 15px;
                    padding: 5px 20px;
                    border: 1px solid #dcdfe6;
                    border-radius: 4px;
                    font-size: 14px;
                }

                .madp-tag-add {
                    margin-left: 5px;
                }
            }
        }
    }
    &-bottom {
        margin-top: 10px;
        padding-top: 10px;
        border-top: 1px solid #e6e6e6;
        &-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        &-avatar {
            width: 32px;
            height: 32px;
            display: block;
            margin: auto;
        }
    }
}
/*上传二位码按钮样式*/
/deep/.madp-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.madp-avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.madp-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}
.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
.madp-guide-language-btn {
    margin-left: 15px;
}
.madp-content-display {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    img {
        max-width: 100px;
    }
    .madp-content-text {
        padding-left: 12px;

        .madp-content-desc {
            font-size: 12px;
            color: #999;
        }
    }
}
.madp-pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}
.madp-table-img {
    img {
        width: 60px;
        height: 60px;
        cursor: url('/img/magnifier.png'), auto;
    }
}
.el-tag {
    margin: 2px;
}
</style>
